package com.xchb.im.server.utils;


import com.xiaoleilu.hutool.json.JSONUtil;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;


@Component
@Slf4j
public class MinioUtils {

    @Value("${minio.endpoint}")
    private String ENDPOINT ;
    @Value("${minio.bucketName}")
    private String BUCKET_NAME;
    @Value("${minio.accessKey}")
    private String ACCESS_KEY;
    @Value("${minio.secretKey}")
    private String SECRET_KEY;

    /**
     * 文件上传
     * @param file
     * @return
     */
    public String upload(MultipartFile file) throws Exception {
        //创建一个MinIO的Java客户端
        MinioClient minioClient =MinioClient.builder()
                .endpoint(ENDPOINT)
                .credentials(ACCESS_KEY,SECRET_KEY)
                .build();
        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKET_NAME).build());
        if (!isExist) {
            //创建存储桶并设置只读权限
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(BUCKET_NAME).build());
            SetBucketPolicyArgs setBucketPolicyArgs = SetBucketPolicyArgs.builder()
                    .bucket(BUCKET_NAME)
                    .config(createBucketPolicyConfigDto(BUCKET_NAME))
                    .build();
            minioClient.setBucketPolicy(setBucketPolicyArgs);
        }

        String filename = file.getOriginalFilename();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        // 设置存储对象名称
        String objectName = sdf.format(new Date()) + "/" + filename;
        // 使用putObject上传一个文件到存储桶中
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(BUCKET_NAME)
                .object(objectName)
                .contentType(file.getContentType())
                .stream(file.getInputStream(), file.getSize(), ObjectWriteArgs.MIN_MULTIPART_SIZE).build();
        minioClient.putObject(putObjectArgs);
        log.info("文件上传成功!");

        String url = ENDPOINT + "/" + BUCKET_NAME + "/" + objectName;

        return url;
    }

    private String createBucketPolicyConfigDto(String bucketName) {
        Map<String,String> statement = new HashMap();
        statement.put("effect","Allow");
        statement.put("principal","*");
        statement.put("action","s3:GetObject");
        statement.put("resource","arn:aws:s3:::"+bucketName+"/*.**");

        Map<String,Object> config = new HashMap();
        config.put("version","2012-10-17");
        config.put("statement", Arrays.asList(statement));

        return JSONUtil.toJsonStr(config);
    }



    public Boolean delete(String objectName) {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(ENDPOINT)
                    .credentials(ACCESS_KEY,SECRET_KEY)
                    .build();
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(BUCKET_NAME).object(objectName).build());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public String uploadBase64(String base64Data) {

        //todo

        return null;
    }
}
